<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\KeywordsReplyStore;
use App\Http\Requests\Admin\NormalReplyStore;
use App\Http\Requests\Admin\SubscribeReplyStore;
use App\Http\Resources\Admin\AutoReplyResource;
use App\Models\KeywordRule;
use App\Models\NormalReply;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;


class WechatAutoRepliesController extends Controller
{
    /**
     * 关键字回复规则列表
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function keywordIndex(Request $request)
    {
        $pageSize = $request->input('page_size');
        $data = KeywordRule::query()->paginate($pageSize);

        return AutoReplyResource::collection($data);
    }

    /**
     * 新建关键字回复规则
     * @param KeywordsReplyStore $request
     * @return mixed
     */
    public function storeKeywordsReply(KeywordsReplyStore $request)
    {
        DB::transaction(function () use ($request) {
            $attribute = $request->only([
                'rule_name', 'keyword',
                'reply_mode', 'status',
            ]);
            $replies = $request->input('replies');
            $attribute['reply_type'] = $replies[0]['type'];
            $attribute['reply_content'] = $replies[0]['content'];
            $rule = new KeywordRule($attribute);
            $rule->save();
            // 处理自定义的回复规则
            $rule->replies()->createMany($request->input('replies'));
        });

        return $this->message('添加成功');
    }

    public function storeNormalReply(NormalReplyStore $request)
    {
        $attribute = $request->only(['material_id', 'type', 'content']);

        $reply = NormalReply::query()->whereNull('event_type')
            ->whereNull('msg_type')
            ->first();
        if (!$reply) {
            NormalReply::query()->create($attribute);
        } else {
            $reply->update($attribute);
        }

        return $this->message('保存成功');
    }

    public function updateKeywordReply()
    {
        // TODO: 更新关键字规则配置
    }

    public function storeSubscribeReply(SubscribeReplyStore $request)
    {
        $attribute = $request->only(['material_id', 'type', 'content']);

        $reply = NormalReply::query()->where('event_type', NormalReply::EVENT_SUBSCRIBE)
            ->first();
        if (!$reply) {
            $attribute['msg_type'] = NormalReply::MSG_EVENT;
            $attribute['event_type'] = NormalReply::EVENT_SUBSCRIBE;
            NormalReply::query()->create($attribute);
        } else {
            $reply->update($attribute);
        }

        return $this->message('保存成功');
    }
}
